import 'package:flutter/material.dart';
import 'package:flutterproject/mvvm/base/base_controller.dart';
import 'package:flutterproject/page/mine/children/order/children/order_detail/order_detail_page.dart';
import 'package:flutterproject/page/product_detail/data/order_success_bean.dart';
import 'package:flutterproject/page/product_detail/data/product_detail_bean.dart';
import 'package:flutterproject/page/product_detail/widget/cart_counter.dart';
import 'package:flutterproject/page/setting/children/address/address_page.dart';
import 'package:flutterproject/page/setting/children/address/data/address_bean.dart';
import 'package:flutterproject/util/address_manager.dart';
import 'package:flutterproject/util/dialog_toast/dialog_util.dart';
import 'package:flutterproject/util/dialog_toast/toast_util.dart';
import 'package:flutterproject/util/extension/extension_util.dart';
import 'package:flutterproject/util/extension/widget_extension.dart';
import 'package:flutterproject/util/http/http_client.dart';
import 'package:flutterproject/util/http/http_exception.dart';
import 'package:flutterproject/util/margin_padding_util.dart';
import 'package:flutterproject/widget/button_common.dart';
import 'package:flutterproject/widget/image_extended.dart';
import 'package:flutterproject/widget/text/text_common.dart';
import 'package:get/get.dart';

class ProductDetailController extends BaseController {
  /// 下单数量
  int number = 1;

  int productId = Get.arguments['id'];

  String imagePre = Get.arguments['name'];

  /// 下单
  Future order(String pwd) async {
    try {
      DialogUtil.showLoading();
      final result =
          await client.post<OrderSuccessBean>(AddressManager.order, data: {
        "addrId": addressBean?.id,
        "num": number,
        "payPassword": pwd,
        "productId": productId
      });
      ToastUtil.showSuccess("下单成功!");
      Get.back();
      Get.off(OrderDetailPage(), arguments: result?.orderId);
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }

  void showPrivacy() {
    DialogUtil.showCustomDialog(
        Container(
          height: 1080.height,
          margin: MarginPaddingUtil.symmetric(horizontal: 61),
          padding: MarginPaddingUtil.symmetric(horizontal: 48),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20.sp),
          ),
          child: Column(
            children: [
              42.heightBox,
              Row(
                children: [
                  TextCommon(
                    "购买协议",
                    size: 28.sp,
                    color: Color(0xFF414141),
                  ),
                  Spacer(),
                  ImageCommon(
                    "/icon/icon_close",
                    size: 26.width,
                    fit: BoxFit.fill,
                  ).addClickEvent(() => DialogUtil.dismiss())
                ],
              ),
              54.heightBox,
              Expanded(
                child: SingleChildScrollView(
                  child: TextCommon(
                    "协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容协议正文内容",
                    size: 24.sp,
                    maxLines: 100,
                    lineHeight: 50.sp,
                    color: Color(0xFF707070),
                  ),
                ),
              ),
              40.heightBox,
              ButtonCommon(
                text: "同意协议",
                onTap: () async {
                  await DialogUtil.dismiss();
                  showSkuSelect();
                },
                fontSize: 32.sp,
                fontColor: Colors.white,
                color: Color(0xFFEDC88B),
                borderRadios: 50,
                fontWeight: FontWeight.bold,
                margin: MarginPaddingUtil.symmetric(horizontal: 141),
                padding: MarginPaddingUtil.symmetric(vertical: 17),
              ),
              85.heightBox
            ],
          ),
        ),
        alignment: Alignment.center);
  }

  List<String> skuColor = ["随机", "白色", "黑色"];
  int _currentSelectSkuColorIndex = 0;

  ProductDetailBean? productDetailBean = ProductDetailBean();
  AddressBean? addressBean = AddressBean();
  HttpClient client = Get.find<HttpClient>();

  @override
  void onReady() {
    super.onReady();
    getDetail();
  }

  /// 获取商品详情
  Future getDetail() async {
    try {
      DialogUtil.showLoading();
      productDetailBean = await client.get<ProductDetailBean>(
          AddressManager.productDetail,
          queryParameters: {"id": productId});
      update();
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }

  /// 获取默认收货地址
  Future<bool> getDefaultAddress() async {
    try {
      DialogUtil.showLoading();
      addressBean = await client.get<AddressBean>(
        AddressManager.defaultAddress,
      );
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }

  Future<void> showSkuSelect() async {
    if (!(await getDefaultAddress())) return;
    showModalBottomSheet(
        isScrollControlled: true,
        context: Get.context!,
        backgroundColor: Colors.transparent,
        builder: (context) {
          return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(20.radius),
                    topRight: Radius.circular(20.radius),
                  ),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    79.heightBox,
                    Row(
                      children: [
                        58.widthBox,
                        ImageAsset(
                          "/image/${imagePre}_2",
                          width: 128.width,
                          height: 128.width,
                          fit: BoxFit.fill,
                          circular: 20.radius,
                        ),
                        32.widthBox,
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            TextCommon(
                              productDetailBean?.title ?? "",
                              size: 28.sp,
                              color: Color(0xFF414141),
                              lineHeight: 40.sp,
                            ),
                            30.heightBox,
                            TextCommon(
                              "${productDetailBean?.price ?? 0.00}",
                              color: Color(0xFFE04D4D),
                              size: 28.sp,
                              fontWeight: FontWeight.bold,
                              lineHeight: 40.sp,
                            ),
                          ],
                        )
                      ],
                    ),
                    Container(
                      color: Colors.white,
                      width: Get.width,
                      padding: MarginPaddingUtil.only(left: 65),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          43.heightBox,
                          Row(
                            children: [
                              TextCommon(
                                "数量",
                                size: 24.sp,
                                color: Color(0xFF414141),
                                fontWeight: FontWeight.bold,
                                lineHeight: 28.sp,
                              ),
                              Spacer(),
                              CartCounter(
                                onChange: (int value) {
                                  number = value;
                                },
                              ),
                              20.widthBox,
                            ],
                          ),
                          41.heightBox,
                          Row(
                            children: [
                              TextCommon(
                                "支付方式",
                                size: 24.sp,
                                color: Color(0xFF414141),
                                fontWeight: FontWeight.bold,
                              ),
                              Spacer(),
                              Container(
                                padding: MarginPaddingUtil.symmetric(
                                    horizontal: 41, vertical: 5),
                                decoration: BoxDecoration(
                                    color: Color(0xFFF6F6F6),
                                    borderRadius: BorderRadius.circular(22.sp)),
                                child: TextCommon(
                                  "酝积分",
                                  size: 24.sp,
                                  color: Color(0xFF707070),
                                  lineHeight: 35.sp,
                                ),
                              ),
                              20.widthBox,
                            ],
                          ),
                          50.heightBox,
                        ],
                      ),
                    ),
                    Container(
                      margin: MarginPaddingUtil.symmetric(horizontal: 20),
                      padding: MarginPaddingUtil.symmetric(
                          vertical: 30, horizontal: 44),
                      decoration: BoxDecoration(
                          border: Border.all(
                              color: Color(0xFF707070).withOpacity(0.5),
                              width: 0.5.width),
                          borderRadius: BorderRadius.circular(10.sp)),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              TextCommon(
                                "收货信息",
                                size: 24.sp,
                                color: Color(0xFF414141),
                                lineHeight: 35.sp,
                                fontWeight: FontWeight.bold,
                              ),
                              40.widthBox,
                              ImageCommon(
                                "/icon/edit",
                                size: 20.width,
                              )
                            ],
                          ),
                          30.heightBox,
                          Row(
                            children: [
                              TextCommon(
                                addressBean?.name ?? "",
                                size: 24.sp,
                                color: Color(0xFF414141),
                                lineHeight: 35.sp,
                                fontWeight: FontWeight.bold,
                              ),
                              60.widthBox,
                              TextCommon(
                                addressBean?.tel ?? "",
                                size: 24.sp,
                                color: Color(0xFF707070),
                                lineHeight: 35.sp,
                              ),
                            ],
                          ),
                          30.heightBox,
                          TextCommon(
                            "${addressBean?.base ?? ""}${addressBean?.detail ?? ""}",
                            size: 24.sp,
                            color: Color(0xFF707070),
                            lineHeight: 35.sp,
                          ),
                        ],
                      ),
                    ).addClickEvent(() async {
                      final result =
                          await Get.to(AddressPage(), arguments: true);
                      if (result != null) {
                        addressBean = result;
                        setState(() {});
                      }
                    }),
                    122.heightBox,
                    ButtonCommon(
                      text: "提交订单",
                      margin: MarginPaddingUtil.symmetric(horizontal: 65),
                      onTap: () async {
                        if (addressBean?.base == null) {
                          ToastUtil.showTips("请先添加收货地址");
                          return;
                        }
                        await DialogUtil.dismiss();
                        DialogUtil.showPwdDialog((value) {
                          order(value);
                        },
                            amount: (number * (productDetailBean?.price ?? 0))
                                .toDouble());
                      },
                      fontSize: 32.sp,
                      fontColor: Colors.white,
                      color: Color(0xFFEDC88B),
                      borderRadios: 50,
                      padding: MarginPaddingUtil.only(top: 25, bottom: 29),
                    ),
                    27.heightBox,
                  ],
                ),
              );
            },
          );
        });
  }
}
